/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package BioHuella;

import adirector.Record;
import adirector.saSpeedMatch;
import pkg1ifxArchivos.cIfxDatosTemplate;
import com.neurotechnology.Fingers.NFExtractor;
import com.neurotechnology.Fingers.Position;
import com.neurotechnology.NImages.NImage;
import com.neurotechnology.NLicensing.NLicensing;
import com.neurotechnology.NLicensing.LicensingConfig;
import com.neurotechnology.NMatcher.NMatcher;
import com.neurotechnology.NMatcher.Speed;
import com.neurotechnology.ScannerMan.ImageScanned;
import com.neurotechnology.ScannerMan.Scanner;
import com.neurotechnology.Templates.NFRecord;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import pkg1ifxArchivos.caDatosTemplate;
import pkg1ifxArchivos.cifxLogs;

public class BioHuella {

    //Strail 8feb2012
    protected static cifxLogs olog=new cifxLogs();
    
    private static final long serialVersionUID = 1L;
    public static final String LIBRARY = "JVFWrapper";
    static BioHuella me;

    NMatcher matcher;
    //NFExtractor extractor;
    RecordDB fdb;

    Scanner[] scanners;
    Position fingerPos;

    NFRecord record;
    NImage image;
    ImageScanned currImageScanner;

    private NImage limage;
    private NImage rimage;

    //Strail 11ene2012
    private int ninicio=0;
    private int nfinal =-1;
    public void setRango(int minicio, int mfinal)
    {
        ninicio=minicio;
        nfinal=mfinal;
    }
    //Strail 13feb2012
    private saSpeedMatch speedmatch;
    //Strail 8feb2012
    private int nMatchingTreshold=90;
    public void setMatchingTreshold(int dato)
    {
        nMatchingTreshold=dato;
        olog.outMensaje("BioHuella.setMatchingTreshold(): (HUELLA) Asignando ("+nMatchingTreshold+") a setFingerMatchingThreshold: " );
        matcher.setFingerMatchingTreshold(nMatchingTreshold);
    }
    public synchronized  void actualizaArrayList(caDatosTemplate odatostemplate)
    {
       //Strail 13feb2012 fdb.actualizarArrayListHuella(odatostemplate);
       //fdb.actualizarArrayListHuella(odatostemplate);
       try{
           //Strail 13feb2012
           Record fr = null;
            for(int i=0; i < odatostemplate.getTemplate().length; i++)
            {
                fr = new Record();
                fr.setName(odatostemplate.getCedulas()[0]);
                fr.setId(odatostemplate.getTemplate()[i].Id);
                fr.setTempalte(odatostemplate.getTemplate()[i].getTemplate());
            }
            //recordsList.add(fr);
           if(fr!=null)
                speedmatch.agregaRecordTemplate(fr);
       }catch(Exception e)
       {
           olog.outMensaje("BioHuella.actualizaArrayList(): (HUELLA) ERROR(0): "+e.getMessage() );
       }

    }

    public BioHuella(int minicio,int mfinal,cifxLogs dlog) {
        try {
            //Strail 8feb2012
            olog=dlog;
            olog.outMensaje("BioHuella.BioHuella(): (HUELLA) Inicio carga de licencias " );
            olog.outMensaje("-----------------------------------------------------------" );
            olog.outMensaje("-(HUELLA) INICIO CARGA DE LICENCIAS                       -" );
            olog.outMensaje("-                                                         -" );
            olog.outMensaje("-                                   <ACEPTAR> <CANCELAR>  -" );
            olog.outMensaje("-----------------------------------------------------------" );

            //JOptionPane.showInputDialog(this, "va a emppezar a cargar las licencias de huella");
            //extractor = new NFExtractor();
            matcher = new NMatcher();
            ninicio=minicio;
            nfinal=mfinal;
            //Strail 13feb2012
            speedmatch = new saSpeedMatch(matcher, null, dlog,0);
            //Strail 13feb2012 fdb = new RecordDB(ninicio,nfinal);
            fdb = new RecordDB(ninicio,nfinal,speedmatch);


        } catch (Exception e) {
            //Strail 8feb2012
            olog.outMensaje("BioHuella.BioHuella(): (HUELLA) ERROR 2: "+e.getMessage() );
            //Strail 8feb2012    e.printStackTrace();
            //Strail 8feb2012    this.print("Unable to load system libraries/n");
        }
        
        //currImageScanner = new Enroller(this, false);
        Exception ex = null;

        try {
                LicensingConfig licConfig = LicensingConfig.getInstance();
                String licensesString = licConfig.getLicenseString("FingersMatcher");
                if (NLicensing.licenseObtain(licConfig.getServerIP(), licConfig.getServerPort(), licensesString)) {
                    if (ex != null) {
                            olog.outMensaje("BioHuella.BioHuella(): (HUELLA) ERROR 3 : Inicializando el ScannerMan  "+ex.getMessage() );
                            //Strail 8feb2012 print("ScannerMan initialization failed!\n");
                            //Strail 8feb2012 print(ex.toString() + "\n");
                    } else
                    {
                        olog.outMensaje("BioHuella.BioHuella(): (HUELLA) OK : Inicializando el ScannerMan  " );
                        //Strail 8feb2012     print("ScannerMan initialization successful\n");
                    }
                } else {
                    olog.outMensaje("BioHuella.BioHuella(): (HUELLA) (ERROR 4) No puedo obtener las licencias  ("+licensesString
                            +")");
                    //Strail 8feb2012    JOptionPane.showMessageDialog(null, "Unable to obtain the following licenses: " + licensesString,
                    //Strail 8feb2012                     "Failed to obtain required licenses", JOptionPane.ERROR_MESSAGE);
                }
        } catch (Exception exc) {
            olog.outMensaje("BioHuella.BioHuella(): (HUELLA) ERROR 5 : "+exc.getMessage() );
            //Strail 8feb2012    System.out.println(exc.getMessage());
            //Strail 8feb2012    exc.printStackTrace(System.err);
        }
        //Strail 8feb2012 matcher.setFaceMatchingThreshold(60);
        //olog.outMensaje("BioHuella.BioHuella(): (HUELLA) Asignando ("+nMatchingTreshold+") a setFingerMatchingThreshold: " );
        matcher.setFingerMatchingTreshold(nMatchingTreshold);
        //Strail 8feb2012
        //matcher.setFingerprintMatchingSpeed(Speed.High);
    }
        
        public synchronized void inserttemplateHuella(String Cedula, byte[] Template) {
            try {
                cIfxDatosTemplate ofceimge = new cIfxDatosTemplate();
                ofceimge.T_Template_Id = Cedula;
                ofceimge.T_Template = Template;
                fdb.almacenar_Huella(ofceimge);
                return;
            } catch (Exception ex) {

                olog.outMensaje("BioHuella.inserttemplateHuella(): (HUELLA) ERROR : "+ex.getMessage() );

            }
        }


        public synchronized String leerTempVerificar(byte[] template,String cedula){

            try{
                identificados=fdb.selectTemplate(template,cedula,matcher);
                
                /*int score = matcher.verify(tempBD, template);
                if(score !=0)
                    identificados="1|"+cedula;
                else
                    identificados="-1|-1";

                 * 
                 */
                return identificados;
            }catch(Exception er)
            {
                olog.outMensaje("BioHuella.leerTempVerificar(): (HUELLA) ERROR : "+er.getMessage() );
                return "";
            }
        }
        public synchronized String leerTempIdentificar(byte[] template){

            try{
                find(template);
                return identificados;
            }catch(Exception er)
            {
                olog.outMensaje("BioHuella.leerTempIdentificar(): (HUELLA) ERROR : "+er.getMessage() );
                return "";
            }
        }
        
        String identificados;
	private synchronized void find(byte[] template) {

            identificados = "";
            identificados=speedmatch.find(template);
//Strail 13feb2012
/**
 *
                int cont = 0 ;
		try {
                    olog.outMensaje("<- BioHuella.find(): Inicio busqueda (HUELLA) "+template.toString());
			matcher.identifyStart(template);
			List<Record> frs = fdb.getRecords();
			for (Record faceRecord : frs) {
				int score = matcher.identifyNext(faceRecord.getTempalte());
				if (score != 0)
                                    identificados = identificados+"|"+faceRecord.getName();

                                cont += 1;
					//print1("Match fount: ID - " + faceRecord.getId() + ", name - " + faceRecord.getName() + ", score - " + score + "\n");
			}
			matcher.identifyEnd();
                        identificados = cont+identificados; //cont+identificados;
                        olog.outMensaje("<- BioHuella.find(): Termina busqueda (HUELLA) : "+identificados);
		} catch (Exception e) {
			//Strail 8feb2012 e.printStackTrace();
                        olog.outMensaje("BioHuella.find(): (HUELLA) ERROR : "+e.getMessage() );
		}
 *
 */
	}
  
         
	void print(String str) {
		System.out.println(str);
	}

//	void setCurrScanner(String currScanner) {
//		this.currScanner.setText(currScanner);
//	}

	void setLimage(NImage limage) {
		this.limage = limage;
	}

	NImage getLimage() {
		return limage;
	}

	void setRimage(NImage rimage) {
		this.rimage = rimage;
	}

	NImage getRimage() {
		return rimage;
	}
        
//        public static void main(String[] args) throws IOException {
//            BioHuella Huella = new BioHuella(); 
//        }
}

//      class ImageFileFilter extends javax.swing.filechooser.FileFilter {
//	String[] extentions;
//
//	ImageFileFilter(String[] extentions) {
//		this.extentions = extentions;
//	}
//
//	public boolean accept(File f) {
//		for (int i = 0; i < extentions.length; i++) {
//			if (f.isDirectory() || f.getName().toLowerCase().endsWith("." + extentions[i].toLowerCase()))
//				return true;
//		}
//		return false;
//	}
//
//	public String getDescription() {
//		String str = "";
//		for (int i = 0; i < extentions.length; i++) {
//			str = str.concat("." + extentions[i]);
//			if (i != extentions.length - 1)
//				str = str.concat(", ");
//		}
//		str = str.concat(" files");
//		return str;
//	}
//}
